<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>我的项目</span>
        </div>
      </template>
      <!-- <el-input
        style="width: 300px; padding-left: 5px"
        @clear="searchOrder"
        clearable
        v-model="searchForm.name"
        placeholder="请输入项目名称"
        class="input-with-select"
      >
        <template #append>
          <el-button icon="Search" @click="searchOrder" />
        </template>
      </el-input> -->
      <span style="font-size: 15px;"> 年份：</span>
      <el-select v-model="searchForm.year" placeholder="Select" style="width: 140px" @change="searchOrder">
        <el-option v-for="item in years" :key="item.year" :value="item.year" />
      </el-select>

      <span style="font-size: 15px; margin-left: 20px"> 月份：</span>
      <el-select v-model="searchForm.month" placeholder="Select" style="width: 80px" @change="searchOrder">
        <el-option v-for="item in 12" :key="item" :value="item" :label="`${item}月`" />
      </el-select>
      <span style="font-size: 15px; margin-left:100px">{{ searchForm.month }}月工分： <el-tag type="info">
          {{ myScore }}
        </el-tag>
      </span>
      <el-button type="warning" plain round @click="showDetail">明细</el-button>
      <div class="myGoodList" v-if="myGoodList.length > 0">
        <h3>你有{{ myGoodList.length }}个项目获得好稿，{{ goodListMessage }}</h3>
        <el-table :data="myGoodList" style="width: 100%; margin-top: 20px" row-class-name="warning-row">
          <el-table-column label="" width=80 align="center">
            <el-button type="danger" :icon="Star" circle />
          </el-table-column>
          <el-table-column prop="product_name" label="项目名称" />
          <el-table-column prop="goodRemark" label="评选理由">
            <template #default="scope">
              <div v-for="(vote, index) in scope.row.votes" :key="index">{{ vote.voter + '： ' + vote.goodRemark }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="goodScore" label="好稿得分" >
            <template #default="scope">
              <div> {{ (scope.row.votes.reduce((sum, vote) => sum + parseInt(vote.goodScore,10), 0) / scope.row.votes.length).toFixed(0) }}</div>
            </template>
            </el-table-column>
        </el-table>
      </div>
      <el-table :data="tableData" :border="parentBorder" style="width: 100%; margin-top: 20px" :row-key="getRowKeys"
        :expand-row-keys="expands" :row-class-name="tableRowClassName" :row-click-expand="true" class="my-table">
        <el-table-column type="expand">
          <template #default="scope">
            <div v-if="Array.isArray(scope.row.files)" style="margin-left: 50px;">
              <div v-if="scope.row.files[0].id != null">
                <div class="files-wrapper">
                  <template v-for="(item, index) in scope.row.files">
                    <div class="file-container" @mouseover="hover = `${scope.$index}-${index}`"
                      @mouseleave="hover = null">
                      <el-image v-if="tool.isImage(item.url)" :src="`${baseURL}/${item.url}`" :zoom-rate="1.2"
                        :max-scale="7" :min-scale="0.2" :initial-index="index" :preview-teleported="true"
                        :preview-src-list="scope.row.files.filter(file => tool.isImage(file.url)).map(file => `${baseURL}/${file.url}`)
                          " fit="cover" class="image" @load="onLoadImage" />
                      <video v-else-if="tool.isVideo(item.url)" :src="`${baseURL}/${item.url}`" controls
                        preload="metadata" class="video"></video>
                      <a :href="`${baseURL}/${item.url}`" class="file-download" target="_blank" v-else>
                        <div class="doc">
                          <span>{{ item.original_name }}</span>
                        </div>
                      </a>
                      <el-button type="danger" :icon="Delete" circle @click="delFile(scope.row.id, item.id)"
                        v-show="hover === `${scope.$index}-${index}`"
                        style="position: absolute;right:10px;bottom:10px;width:30px;height:30px" />
                    </div>
                  </template>

                  <el-upload v-model:file-list="scope.row.fileList" class="upload-demo" :action="`${baseURL}/api/upload`"
                    :on-preview="handlePreview" :on-remove="handleRemove"
                    :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, scope.row.id, scope.row.product_name)"
                    :data="{ rowId: scope.row.id, product_name: scope.row.product_name }" multiple :name="'files'"
                    list-type="picture-card" style="display:inline-block; vertical-align: bottom;margin:8px">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                </div>
              </div>
              <div v-else>
                <el-upload v-model:file-list="scope.row.fileList" class="upload-demo" :action="`${baseURL}/api/upload`"
                  :on-preview="handlePreview" :on-remove="handleRemove"
                  :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, scope.row.id, scope.row.product_name)"
                  :data="{ rowId: scope.row.id, product_name: scope.row.product_name }" multiple :name="'files'"
                  list-type="picture-card" style="display:inline-block; vertical-align: bottom;">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="项目名称">
          <template #default="{ row }">
            <el-input v-model="row.product_name" v-if="row.isEditing && row.big_id == null"
              placeholder="这里填写项目名称"></el-input>
            <span v-else>{{ row.product_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="department_name" label="部门">
          <template #default="{ row }">
            <el-select v-model="row.department_name" v-if="row.isEditing && row.big_id == null" placeholder="请选择部门">
              <el-option v-for="dept in departments" :key="dept.id" :label="dept.name" :value="dept.name" />
            </el-select>
            <span v-else>{{ row.department_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注">
          <template #default="{ row }">
            <el-input v-model="row.remark" v-if="row.isEditing" :rows="5" type="textarea" placeholder="这里填写备注"></el-input>
            <span v-else v-html="formatRemark(row.remark)"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="{ row }">
            <el-button type="primary" @click="editRow(row)" v-if="!row.isEditing">编辑</el-button>
            <el-button type="primary" @click="submitRow(row)" v-else>提交</el-button>
            <el-button v-if="row.big_id === null || !row.big_id" type="danger" @click="delRow(row)">
              删除
            </el-button>
            <el-button v-else type="success" @click="moveRow(row)" :disabled="checkScore(row)" >
              放到下一个月
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-button class="mt-4" style="width: 100%;margin:20px 0" @click="addRow" type="success">
        新增项目
      </el-button>
    </el-card>
    <el-drawer v-model="showDrawer" :title="searchForm.year + '年' + searchForm.month + '月工分明细表'" direction="rtl"
      size="50%">
      <el-table :data="myScoreList" stripe>
        <el-table-column property="product_name" label="项目名称" />
        <el-table-column property="average_score" label="得分" />
        <el-table-column property="score_remark" label="打分备注">
          <template #default="scope">
            {{ scope.row.scores.map(item => item.score_remark !== null ? item.score_remark : '').join(', ') }}
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Star } from '@element-plus/icons-vue'
import workApi from '../../api/work'
import fileApi from '../../api/file'
import tool from '../../tools/tool'
const parentBorder = ref(true)
const tableData = ref([])
const myGoodList = ref([])
const years = ref()
const months = ref()
const myScore = ref()
const isAdding = ref(false)
const departments = ref([])
const hover = ref(null)
const expands = ref([]) // 要展开的行，数值的元素是row的key值

const showDrawer = ref(false)
const myScoreList = ref()

// 获取全局变量
const baseURL = window.globalConfig.baseURL
const username = sessionStorage.getItem('username')
const type = sessionStorage.getItem('type')

// 搜索条件
const searchForm = reactive({
  username: username,
  name: '',
  year: '',
  month: '',
})

onMounted(async () => {
  const yearRes = await workApi.getDistinctYears()
  years.value = yearRes.data
  console.log(years.value)
  //默认今年
  const currentYear = new Date().getFullYear()
  searchForm.year = currentYear

  //默认当月
  const currentMonth = new Date().getMonth() + 1
  searchForm.month = currentMonth

  //请求部门列表
  const departmentRes = await workApi.getDepartments()
  departments.value = departmentRes.data

  searchOrder()
})

// 获取数据列表
const searchOrder = async () => {
  isAdding.value = false
  const res = await workApi.getMyListByMonth(searchForm)
  const resData = res.data
  console.log(res.data)
  // 创建一个 Map 对象，用于存储相同 id 的数据
  const idMap = new Map()

  // 遍历数据数组，将具有相同 id 的数据的 url 合并到一个数组中
  resData.forEach((item) => {
    const id = item.id;
    if (idMap.has(id)) {
      idMap.get(id).files.push({ id: item.file_id, url: item.url, original_name: item.original_name });
    } else {
      idMap.set(id, { ...item, files: [{ id: item.file_id, url: item.url, original_name: item.original_name }] });
    }
  });

  // 将 Map 对象转换为数组
  const result = Array.from(idMap.values())
  tableData.value = result
  console.log(tableData.value)

  getMyScoreByMonth()

  // 创建一个 Map 对象，用于存储相同 id 的数据
  const goodMap = new Map()
  //这里把当月所有好稿都列出来
  const resGood = await workApi.getMyGoodListByMonth(searchForm)
  // 遍历数据数组，将具有相同 id 的数据的 url 合并到一个数组中
  resGood.data.forEach((item) => {
    const id = item.order_id;
    if (goodMap.has(id)) {
      goodMap.get(id).votes.push({ voter: item.voter, goodRemark: item.remark,goodScore:item.score });
    } else {
      goodMap.set(id, { ...item, votes: [{ voter: item.voter, goodRemark: item.remark,goodScore:item.score }] });
    }
  });
  // 将 Map 对象转换为数组
  const result1 = Array.from(goodMap.values());
  myGoodList.value = result1
  //这里把当月所有好稿都列出来 end
}

// 获取row的key值
const getRowKeys = (row) => {
  return row.id;
}

const tableRowClassName = (row) => {
  if (row.row.big_id != null) {
    return 'highlight-row'; // 自定义高亮样式
  }
  return '';
}


const addRow = () => {
  if (!isAdding.value) {
    tableData.value.push({ product_name: '', department_name: '', remark: '', isEditing: true });
    isAdding.value = true;
    nextTick(() => {   //每次让滚动条滚到底部
      const main = document.querySelector('.el-main');
      if (main) {
        main.scrollTop = main.scrollHeight;
      }
    });
  }
}

const editRow = (row) => {
  row.isEditing = true;
};

const submitRow = async (row) => {
  if (row) {
    //判断是否正确输入
    if (!row.product_name || !row.department_name) {
      ElMessage.warning('请填写项目名称和部门')
      return
    }

    row.isEditing = false;
    isAdding.value = false;

    const data = {
      id: row.id || 'new',
      product_name: row.product_name,
      department_name: row.department_name,
      remark: row.remark,
      member: username,
      type: type,
      work_date: searchForm.year + '-' + searchForm.month,
      username: username
    }

    const res = await workApi.handleMyOrder(data)
    // 处理后台返回的结果，你可以根据具体情况进行处理
    if (res.data.success) {
      ElMessage.success('更新成功')
      searchOrder()
    } else {
      ElMessage.error('更新失败')
    }
  }
}

const delRow = (row) => {
  if (row.id) {
    ElMessageBox.confirm('确定要删除该项目吗?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const res = await workApi.delMyOrder({ id: row.id, username: username })
        if (res.data.success) {
          ElMessage.success('删除成功')
          searchOrder()
        } else {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  } else {
    tableData.value.splice(tableData.value.length - 1, 1);
    row.isEditing = false;
    isAdding.value = false;
  }
}

const delFile = async (rowId, file_id) => {
  ElMessageBox.confirm('确定要删除该文件吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await fileApi.delFile({ id: file_id, username: username })
      if (res.data.success) {
        ElMessage.success('删除成功')
        searchOrder()
        expands.value.push(rowId);  //展开操作这行
      } else {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const handleSuccess = (response, file, fileList, rowId, product_name) => {
  console.log('File uploaded successfully:', response);
  ElMessage.success('上传成功')
  searchOrder()
  expands.value.push(rowId);  //展开操作这行
}


//获取当月我的工分
const getMyScoreByMonth = async () => {
  const res = await workApi.getMyScoreByMonth(searchForm)
  const resData = res.data
  // 创建一个 Map 对象，用于存储相同 id 的数据
  const idMap = new Map()
  // 遍历数据数组，将具有相同 id 的数据的 url 合并到一个数组中
  resData.forEach((item) => {
    const id = item.id;
    if (idMap.has(id)) {
      idMap.get(id).scores.push({ score: item.score, scorer: item.scorer, score_remark: item.score_remark });
    } else {
      idMap.set(id, { ...item, scores: [{ score: item.score, scorer: item.scorer, score_remark: item.score_remark }] });
    }
  });

  // 将 Map 对象转换为数组
  const result = Array.from(idMap.values());

  result.forEach((item) => {
    // 给每条记录加上一个平均分
    if (item.scores && item.scores.length > 0) {
      const totalScore = item.scores.reduce((sum, scoreObj) => sum + scoreObj.score, 0);
      const averageScore = totalScore / item.scores.length;
      item.average_score = averageScore;
    } else {
      item.average_score = '0'; // 如果没有 scores，平均分为 0
    }
  })
  myScoreList.value = result
  myScore.value = result.reduce((total, row) => {
    return total + (row.average_score || 0);
  }, 0);
  if (myScore.value == 0) {
    myScore.value = '暂无分数'
  }
}

const showDetail = () => {
  if (myScore.value != '暂无分数') {
    showDrawer.value = true
  } else {
    ElMessage.error('该月还没有打分');
    return;
  }
}

const onLoadImage = (event) => {
  const img = event.target
  const isHorizontal = img.naturalWidth < img.naturalHeight

  // 直接修改图片的样式
  img.style.height = isHorizontal ? '200px' : 'auto'
  img.style.width = isHorizontal ? 'auto' : '200px'
}

const formatRemark = (remark) => {
  if (!remark) return '';

  // 正则表达式匹配 URL
  const urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;

  // 将 URL 替换为超链接并替换换行符为 <br>
  return remark
    .replace(urlPattern, (url) => `<a href="${url}" target="_blank">${url}</a>`)
    .replace(/\n/g, '<br>');
};

const goodListMessage = computed(() => {
  const length = myGoodList.value.length;
  if (length == 1) {
    return '很棒哟！';
  } else if (length == 2) {
    return '太厉害了！';
  } else if (length >= 3) {
    return '非常出色！';
  }
});

const checkScore = (row) => {
  if (!myScoreList.value) {
        return false;
      }
  const foundItem = myScoreList.value.find(item => item.id === row.id);
  if (foundItem) {
    return foundItem.score!== null;
  }
  // 如果没有找到对应项，默认允许点击
  return false;
};

// 移动方法
const moveRow = (row) => {
  if (row.id) {
    ElMessageBox.confirm('确定要放到下一个月吗?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const res = await workApi.moveToNextMonth({ id: row.id, work_date:row.work_date,username: username })
        if (res.data.success) {
          ElMessage.success('已移到下一个月')
          searchOrder()
        } else {
          ElMessage.error('移动失败')
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
      })
  } 
};



</script>

<style scoped>
.add {
  float: right;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 100%;
  height: 100%;
}

.el-tag {
  margin: 5px 5px 5px 0;
}

.files-wrapper {
  display: flex;
  flex-wrap: wrap;
  /* 允许换行 */
  align-items: flex-start;
  /* 确保所有项在交叉轴（垂直方向）上对齐 */
}

.file-container {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
  /* 防止图片超出容器 */
  border: 1px solid #dcdcdc;
  /* 可以根据需要添加边框 */
  border-radius: 8px;
  /* 圆角效果 */
  background-color: #f9f9f9;
  /* 背景颜色 */
  margin: 8px;
}

.file-container .image,
.file-container .video {
  transition: transform 0.3s linear;
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.file-container:hover .image,
.file-container:hover .doc,
.file-container:hover .video {
  transform: scale(1.05);
}

.file-container .video {
  width: 100%;
  /* 确保视频宽度填满容器 */
  height: auto;
  /* 让高度自适应 */
}


.doc {
  width: 150px;
  height: 150px;
  border: 1px solid #9bb0e0;
  margin: 0 10px;
  padding: 10px;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #f6f8fc, #e9eef9);
  transition: transform 0.3s linear;
}

.doc span {
  display: inline-block;
  vertical-align: middle;
  padding: 0 10px;
  width: 60%;
  overflow: hidden;
  white-space: normal;
  word-wrap: break-word;
  line-height: normal;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  color: #6a6a6b;
  font-weight: bold;
}

:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

:deep(.success-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.myGoodList {
  border: 2px solid rgb(161, 48, 3);
  border-radius: 20px;
  margin: 20px 0;
  padding: 0 20px 20px;
  box-shadow: 0 0 10px rgba(161, 84, 3);
}

.myGoodList h3 {
  color: rgba(161, 48, 3);
  text-align: center;
}

:deep() .highlight-row {
  background-color: #e0e0e0;
  /* 浅绿色背景 */
}
</style>
